<?php
namespace App\Modules\Relationship\Models;


use App\Http\Services\CommonServices;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use App\Http\Model\Base;
use phpDocumentor\Reflection\Types\Null_;

class RelationshipIntimacyLogModel extends Base {

    protected $table = "rs_relationship_intimacy_log";

    protected $fields = ['id',
        'rs_code as rsCode',
        'task_id as taskId',
        'intimate_before as intimateBefore',
        'intimate_change as intimateChange',
        'intimate_after as intimateAfter',
        'change_type as changeType',
        'type',
        'created_time as createdTime'];
    protected $tablePrefix = '';
    public function __construct(array $attributes = [])
    {
        parent::__construct($this->table, $attributes);
        $this->tablePrefix = env('DB_PREFIX');
    }

    // 写入亲密值增长日志
    public function  addLog (array $data) {
        if (!$data) {
            return false;
        }
        $insertData = [
            'rs_code'=>$data['rsCode'],
            'task_id'=>$data['taskId'],
            'intimate_before'=>$data['intimateBefore'],
            'intimate_change'=>$data['intimateChange'],
            'intimate_after'=>$data['intimateAfter'],
            'change_type'=>$data['changeType'],
            'type'=>$data['type']
        ];
        DB::table($this->table)->insert($insertData);
    }

    public function getTasks($type, $rsCode, $startTime, $endTime){
        $table = $this->tablePrefix . $this->table;
        $sql = "SELECT task_id as taskId, sum(intimate_change) as intimacyChange FROM {$table} 
        WHERE rs_code = ?
        AND created_time >= ?
        AND created_time < ? 
        AND type = ?
        AND change_type = 1
        AND is_deleted = 0
        GROUP BY task_id";
        $bindings = array($rsCode, $startTime, $endTime, $type);
        $rows = DB::select($sql, $bindings);
        return self::objToArray($rows);
    }

    //
    public function getOneTaskByRscode ($type, $rsCode, $startTime, $endTime, $taskId) {
        $table = $this->tablePrefix . $this->table;
        $sql = "SELECT task_id as taskId, sum(intimate_change) as intimacyChange FROM {$table} 
        WHERE rs_code = ?
        AND created_time >= ?
        AND created_time < ? 
        AND type = ?
        AND change_type = 1
        AND is_deleted = 0
        AND task_id = ?";
        $bindings = array($rsCode, $startTime, $endTime, $type, $taskId);
        $rows = DB::select($sql, $bindings);
        if ($rows[0]->intimacyChange == null) {
            return null;
        }
        return self::objToArray($rows[0]);
    }



    public function deleteRecord ($data = array()) {
        return DB::table($this->table)->where($data)->update(array('is_deleted'=>1));
    }
}

